package cn.edu.ujn.lab3.web;

import cn.edu.ujn.lab3.dao.*;
import cn.edu.ujn.lab3.service.BaseDictService;
import cn.edu.ujn.lab3.service.VehicleService;
import cn.edu.ujn.lab3.utils.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 车辆信息管理控制器类
 */
@Controller
@RequestMapping("/vehicle")
public class VehicleController {

	@Autowired
	private BaseDictService baseDictService;
	@Autowired
    private VehicleService vehicleService;
	private String VEHICLE_TYPE="060";

	/**
	 *  车辆列表
	 */
	@RequestMapping(value = "/list.action")
	public String list(@RequestParam(defaultValue="1")Integer page,
			@RequestParam(defaultValue="10")Integer rows,
                       String vehicleNo, String vehicleType,
			 Model model) {
		// 条件查询所有车辆
		Page<Vehicle> vehicleList = vehicleService
				.findVehicleList(page, rows, vehicleNo,
                        vehicleType);
		model.addAttribute("page", vehicleList);
		// 仓库字典
		List<BaseDict> vehicleTypes = baseDictService
				.findBaseDictByTypeCode(VEHICLE_TYPE);
        // 添加参数
        model.addAttribute("vehicleTypes", vehicleTypes);
		model.addAttribute("vehicleNo", vehicleNo);
		model.addAttribute("vehicleType", vehicleType);
		return "vehicle";
	}
	
	/**
	 * 创建车辆
	 */
	@RequestMapping("/create.action")
	@ResponseBody
	public String vehicleCreate(Vehicle vehicle,HttpSession session) {
	    // 获取Session中的当前用户信息
	    User user = (User) session.getAttribute("USER_SESSION");
        vehicle.setUserId(user.getUser_id());
        vehicle.setUserName(user.getUser_name());
	    int rows = vehicleService.createVehicle(vehicle);
	    if(rows > 0){
	        return "OK";
	    }else{
	        return "FAIL";
	    }
	} 

	/**
	 * 通过id获取车辆信息
	 */
	@RequestMapping("/getVehicleById.action")
	@ResponseBody
	public Vehicle getVehicleById(Integer id) {
        Vehicle vehicle = vehicleService.getVehicleById(id);
	    return vehicle;
	}
	/**
	 * 更新车辆
	 */
	@RequestMapping("/update.action")
	@ResponseBody
	public String vehicleUpdate(Vehicle vehicle) {
	    int rows = vehicleService.updateVehicle(vehicle);
	    if(rows > 0){
	        return "OK";
	    }else{
	        return "FAIL";
	    }
	}

	/**
	 * 删除车辆
	 */
	@RequestMapping("/delete.action")
	@ResponseBody
	public String vehicleDelete(Integer id) {
	    int rows = vehicleService.deleteVehicle(id);
	    if(rows > 0){			
	        return "OK";
	    }else{
	        return "FAIL";			
	    }
	}

}

